{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
module Session(readSession, writeSession, Session(..), UserID(..)) where


import Happstack.Server (Response, FilterMonad)
import Happstack.Server.RqData (HasRqData, lookCookieValue)
import Happstack.Server.Cookie (mkCookie, addCookie)
import Happstack.Server.Internal.Cookie (CookieLife(MaxAge))
import Control.Monad.IO.Class (MonadIO)
import Session.Security(encryptSession, decryptSession)
import Control.Monad (MonadPlus(..), MonadPlus)

newtype UserID = UserID String deriving (Show, Read)
data Session = Session UserID deriving (Show, Read)

cookieName = "session_v0"

readSession :: (HasRqData m, Monad m, MonadPlus m, Functor m) => m (Maybe Session)
readSession =  fmap decryptSession (lookCookieValue cookieName) `mplus` return Nothing

writeSession :: (MonadIO m, FilterMonad Response m, HasRqData m, Monad m, Functor m) => Session -> m ()
writeSession = addCookie (MaxAge $ 60) . mkCookie cookieName . encryptSession
